<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
      <el-form-item label="应用名称" prop="applicantName">
        <el-input v-model="queryParams.applicantName" placeholder="请输入应用名称" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="applicantAvl">
        <el-select v-model="queryParams.applicantAvl" placeholder="应用状态" clearable style="width: 240px">
          <el-option v-for="dict in statusList" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" v-hasPermi="['gc:yygl:xz']" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :scrollbar-always-on="true" :data="applicantList">
      <el-table-column label="序号" type="index" width="100" />
      <el-table-column label="应用编号" prop="applicantId" width="300" />
      <el-table-column label="应用名称" prop="applicantName" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="应用描述" prop="applicantDesc" :show-overflow-tooltip="true" width="300" />
      <el-table-column label="状态" align="center" width="100">
        <template #default="scope">
          <el-switch v-model="scope.row.applicantAvl" @change="handleapplicantAvlChange(scope.row)" active-value="Y"
            inactive-value="N"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button v-hasPermi="['gc:yygl:xg']" link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button v-hasPermi="['gc:yygl:cdqx']" link type="primary" @click="handleDownLoad(scope.row)">菜单权限</el-button>
          <el-button v-hasPermi="['gc:yygl:sc']" link type="primary" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改应用配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="应用名称" prop="applicantName">
          <el-input v-model="form.applicantName" placeholder="请输入应用名称" />
        </el-form-item>
        <el-form-item label="应用描述">
          <el-input v-model="form.applicantDesc" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.applicantAvl">
            <el-radio v-for="dict in statusList" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.menuCheckStrictly"
            @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <el-tree class="tree-border" :data="menuOptions" show-checkbox ref="menuRef" node-key="id"
            :check-strictly="!form.menuCheckStrictly" empty-text="加载中，请稍候"
            :props="{ label: 'label', children: 'children' }"></el-tree>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配应用数据权限对话框 -->
    <el-dialog :title="title" v-model="openDataScope" width="500px" append-to-body>
      <el-form :model="form" label-width="150px">
        <el-form-item label="应用名称">
          <el-input v-model="form.applicantName" :disabled="true" />
        </el-form-item>
        <el-form-item label="菜单数据权限">
          <el-tree class="tree-border" :data="deptOptions" ref="deptRef" node-key="id"
            :check-strictly="!form.deptCheckStrictly" empty-text="加载中，请稍候"
            :props="{ label: 'label', children: 'children' }">
            <template #default="{ node, data }">
              <div class="custom-tree-node">
                <span class="tree-label" :title="node.label">{{ node.label }}</span>
                <el-button link type="primary" style="margin-left: 20%;"
                  @click.stop="DownLoad(node,data)">下发</el-button>
              </div>
            </template>
          </el-tree>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="ApplicationIndex">
  import {
    addapplicant,
    delapplicant,
    getapplicant,
    listapplicant,
    updateapplicant,
    allTree,
    changeRoleapplicantAvl,
    AppliMenu
  } from "@/api/system/applicant";

  const router = useRouter();
  const { proxy } = getCurrentInstance();
  const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

  const applicantList = ref([]);
  const open = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref("");
  const dateRange = ref([]);
  const menuOptions = ref([]);
  const menuExpand = ref(false);
  const menuNodeAll = ref(false);
  const deptExpand = ref(true);
  const deptNodeAll = ref(false);
  const deptOptions = ref([]);
  const openDataScope = ref(false);
  const menuRef = ref(null);
  const deptRef = ref(null);
  const statusList = ref([{
    label: '启用',
    value: 'Y'
  }, {
    label: '禁用',
    value: 'N'
  }])
  /** 数据范围选项*/
  const dataScopeOptions = ref([
    { value: "1", label: "全部数据权限" },
    { value: "2", label: "自定数据权限" },
    { value: "3", label: "本部门数据权限" },
    { value: "4", label: "本部门及以下数据权限" },
    { value: "5", label: "仅本人数据权限" }
  ]);

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      applicantName: undefined,
      applicantAvl: undefined
    },
    rules: {
      applicantName: [{ required: true, message: "应用名称不能为空", trigger: "blur" }],
    },
  });

  const { queryParams, form, rules } = toRefs(data);

  /** 查询应用列表 */
  function getList() {
    loading.value = true;
    listapplicant(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
      applicantList.value = response.rows
      total.value = response.total;
      loading.value = false;
    });
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    dateRange.value = [];
    proxy.resetForm("queryRef");
    handleQuery();
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const applicantIds = row.applicantId || ids.value;
    proxy.$modal.confirm('是否确认删除应用编号为"' + applicantIds + '"的数据项?').then(function() {
      return delapplicant(applicantIds);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download("system/role/export", {
      ...queryParams.value,
    }, `role_${new Date().getTime()}.xlsx`);
  }


  /** 应用状态修改 */
  function handleapplicantAvlChange(row) {
    let text = row.applicantAvl === "Y" ? "启用" : "停用";
    proxy.$modal.confirm('确认要"' + text + '""' + row.applicantName + '"应用吗?').then(function() {
      return changeRoleapplicantAvl({
        applicantId: row.applicantId,
        applicantAvl: row.applicantAvl
      });
    }).then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    }).catch(function() {
      row.applicantAvl = row.applicantAvl === "Y" ? true : false;
    });
  }

  /** 更多操作 */
  function handleCommand(command, row) {
    switch (command) {
      case "handleDataScope":
        handleDataScope(row);
        break;
      case "handleAuthUser":
        handleAuthUser(row);
        break;
      default:
        break;
    }
  }

  /** 分配用户 */
  function handleAuthUser(row) {
    router.push("/system/role-auth/user/" + row.applicantId);
  }

  /** 查询菜单树结构 */
  function getMenuTreeselect() {
    allTree().then(response => {
      menuOptions.value = response.data;
    });
  }

  /** 所有部门节点数据 */
  function getDeptAllCheckedKeys() {
    // 目前被选中的部门节点
    let checkedKeys = deptRef.value.getCheckedKeys();
    // 半选中的部门节点
    let halfCheckedKeys = deptRef.value.getHalfCheckedKeys();
    checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
    return checkedKeys;
  }

  /** 重置新增的表单以及其他数据  */
  function reset() {
    if (menuRef.value != undefined) {
      menuRef.value.setCheckedKeys([]);
    }
    menuExpand.value = false;
    menuNodeAll.value = false;
    deptExpand.value = true;
    deptNodeAll.value = false;
    form.value = {
      applicantId: undefined,
      applicantName: undefined,
      roleKey: undefined,
      roleSort: 0,
      applicantAvl: "Y",
      menuIds: [],
      deptIds: [],
      menuCheckStrictly: true,
      deptCheckStrictly: true,
      applicantDesc: undefined
    };
    proxy.resetForm("roleRef");
  }

  /** 添加应用 */
  function handleAdd() {
    reset();
    getMenuTreeselect();
    open.value = true;
    title.value = "添加应用";
  }

  function handleDownLoad(row) {
    const applicantId = row.applicantId || ids.value;
    getapplicant(applicantId).then(response => {
      form.value = response.data;
      deptOptions.value = response.data.menuTree;
      openDataScope.value = true;
      title.value = "分配数据权限";
    });
  }

  function DownLoad(row, data) {
    const applicantId = row.applicantId || ids.value;
    proxy.$modal.confirm(`是否同步授权${form.value.applicantName}给现有租户`).then(function() {
      return AppliMenu({ applicantId: form.value.applicantId, menuId: data.id });
    }).then(() => {
      proxy.$modal.msgSuccess("下发成功");
    }).catch(function() {});
  }
  /** 修改应用 */
  function handleUpdate(row) {
    reset();
    const applicantId = row.applicantId || ids.value;
    const roleMenu = allTree();
    getapplicant(applicantId).then(response => {
      form.value = response.data;
      form.value.roleSort = Number(form.value.roleSort);
      form.value.menuCheckStrictly = true;
      form.value.deptCheckStrictly = true;
      open.value = true;
      nextTick(() => {
        roleMenu.then((res) => {
          menuOptions.value = res.data;
          response.data.menuIds.forEach((v) => {
            nextTick(() => {
              menuRef.value.setChecked(v, true, false);
            });
          });
        })
      });
      console.log(menuOptions)
      title.value = "修改应用";
    });
  }

  /** 根据应用ID查询菜单树结构 */
  function getapplicantMenuTreeselect(applicantId) {
    return roleMenuTreeselect(applicantId).then(response => {
      menuOptions.value = response.menus;
      return response;
    });
  }


  /** 树权限（展开/折叠）*/
  function handleCheckedTreeExpand(value, type) {
    if (type == "menu") {
      let treeList = menuOptions.value;
      for (let i = 0; i < treeList.length; i++) {
        menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
      }
    } else if (type == "dept") {
      let treeList = deptOptions.value;
      for (let i = 0; i < treeList.length; i++) {
        deptRef.value.store.nodesMap[treeList[i].id].expanded = value;
      }
    }
  }

  /** 树权限（全选/全不选） */
  function handleCheckedTreeNodeAll(value, type) {
    if (type == "menu") {
      menuRef.value.setCheckedNodes(value ? menuOptions.value : []);
    } else if (type == "dept") {
      deptRef.value.setCheckedNodes(value ? deptOptions.value : []);
    }
  }

  /** 树权限（父子联动） */
  function handleCheckedTreeConnect(value, type) {
    if (type == "menu") {
      form.value.menuCheckStrictly = value ? true : false;
    } else if (type == "dept") {
      form.value.deptCheckStrictly = value ? true : false;
    }
  }

  /** 所有菜单节点数据 */
  function getMenuAllCheckedKeys() {
    // 目前被选中的菜单节点
    let checkedKeys = menuRef.value.getCheckedKeys();
    // 半选中的菜单节点
    let halfCheckedKeys = menuRef.value.getHalfCheckedKeys();
    checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
    return checkedKeys;
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["roleRef"].validate(valid => {
      if (valid) {
        if (form.value.applicantId != undefined) {
          form.value.menuIds = getMenuAllCheckedKeys();
          updateapplicant(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          form.value.menuIds = getMenuAllCheckedKeys();
          addapplicant(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      }
    });
  }

  /** 取消按钮 */
  function cancel() {
    open.value = false;
    reset();
  }


  getList();
</script>